Golang
測試
轉換一下心情,來嘗試看看單元測試好了
在golang上要跑測試的話,可以考慮先試看看內建 testing 套件。
首先,我們需要先import testing,之後跟很多單元測試雷同,我們需要讓function name做點變化,func TestXxx
大致上需要注意以下的幾個規則
先來看 The Go Playground的test 範例,原版是下面這樣
package main
import (
"testing"
)
// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes somes tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
for i := len(list) - 1; i > 0; i-- {
if list[i] == x {
return i
}
}
return -1
}
func TestLastIndex(t *testing.T) {
tests := []struct {
list []int
x int
want int
}{
{list: []int{1}, x: 1, want: 0},
{list: []int{1, 1}, x: 1, want: 1},
{list: []int{2, 1}, x: 2, want: 0},
{list: []int{1, 2, 1, 1}, x: 2, want: 1},
{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: 0},
}
for _, tt := range tests {
if got := LastIndex(tt.list, tt.x); got != tt.want {
t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
}
}
}
我們來改個版本看看
package main
import (
"testing"
)
// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes somes tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
for i := len(list) - 1; i > 0; i-- {
if list[i] == x {
return i
}
}
return -1
}
func TestLastIndex(t *testing.T) {
tests := []struct {
list []int
x int
want int
}{
{list: []int{1}, x: 1, want: -1},
{list: []int{1, 1}, x: 1, want: 1},
{list: []int{2, 1}, x: 2, want: -1},
{list: []int{1, 2, 1, 1}, x: 2, want: 1},
{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: -1},
}
for _, tt := range tests {
if got := LastIndex(tt.list, tt.x); got != tt.want {
t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
}
}
}
這樣跑我們就可以得到PASS,就是驗證都符合我們要的結果,那如果跑回原本的CASE,則會出現FAIL。
參考資料
https://pkg.go.dev/testing
https://play.golang.org/